package org.microframework.cloud.files.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.microframework.base.core.security.annotation.RequiresLogin;
import org.microframework.base.core.security.annotation.RequiresPermissions;
import org.microframework.base.core.security.utils.SecurityUtils;
import org.microframework.cloud.files.model.ApiResponse;
import org.microframework.cloud.files.model.FileInfo;
import org.microframework.cloud.files.service.MinioFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 安全文件管理控制器
 * 
 * 该控制器整合了micro-base-security，提供需要认证和授权的文件管理功能
 */
@Slf4j
@RestController
@RequestMapping("/api/secure-files")
@Tag(name = "安全文件管理", description = "需要认证和授权的文件操作")
public class SecureFileController {

    private final MinioFileService fileService;

    @Autowired
    public SecureFileController(MinioFileService fileService) {
        this.fileService = fileService;
    }

    /**
     * 上传私有文件，需要登录
     */
    @PostMapping("/upload")
    @RequiresLogin
    @Operation(summary = "上传私有文件", description = "上传文件到私有存储区域，需要登录")
    public ApiResponse<FileInfo> uploadSecureFile(
            @Parameter(description = "文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "目录路径") @RequestParam(value = "directory", required = false) String directory) {
        
        // 获取当前登录用户信息
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        log.info("用户[{}:{}]上传私有文件: {}, 目录: {}", userId, username, file.getOriginalFilename(), directory);
        
        // 使用用户ID创建用户专属目录
        String userDirectory = userId + "/" + (directory != null ? directory : "");
        
        // 上传到私有存储区
        FileInfo fileInfo = fileService.uploadFile(file, false, userDirectory);
        return ApiResponse.success(fileInfo);
    }

    /**
     * 删除私有文件，需要文件管理权限
     */
    @DeleteMapping("/{fileId}")
    @RequiresPermissions("file:delete")
    @Operation(summary = "删除私有文件", description = "删除私有文件，需要文件管理权限")
    public ApiResponse<Boolean> deleteSecureFile(
            @Parameter(description = "文件ID") @PathVariable String fileId) {
        
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        log.info("用户[{}:{}]删除文件: {}", userId, username, fileId);
        
        // 获取文件信息，验证文件所有权
        FileInfo fileInfo = fileService.getFileInfoById(fileId);
        if (fileInfo != null && fileInfo.getObjectName() != null) {
            // 检查文件是否属于当前用户
            if (fileInfo.getObjectName().startsWith(userId + "/")) {
                boolean result = fileService.deleteFile(fileId);
                return ApiResponse.success(result);
            } else {
                return ApiResponse.error(403, "无权删除其他用户的文件");
            }
        }
        
        return ApiResponse.error(404, "文件不存在");
    }

    /**
     * 获取当前用户的文件列表
     */
    @GetMapping("/my-files")
    @RequiresLogin
    @Operation(summary = "获取我的文件", description = "获取当前登录用户的文件列表")
    public ApiResponse<List<FileInfo>> getMyFiles(
            @Parameter(description = "目录路径") @RequestParam(value = "directory", required = false) String directory) {
        
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        log.info("用户[{}:{}]获取个人文件列表, 目录: {}", userId, username, directory);
        
        // 构建用户目录
        String userDirectory = userId + "/" + (directory != null ? directory : "");
        
        // 获取用户目录下的文件
        List<FileInfo> files = fileService.listFiles(userDirectory, false);
        return ApiResponse.success(files);
    }

    /**
     * 管理员查看所有用户的文件，需要管理员权限
     */
    @GetMapping("/all")
    @RequiresPermissions("file:view:all")
    @Operation(summary = "查看所有文件", description = "管理员查看所有用户的文件，需要管理员权限")
    public ApiResponse<List<FileInfo>> getAllFiles(
            @Parameter(description = "目录路径") @RequestParam(value = "directory", required = false) String directory,
            @Parameter(description = "是否查询公共存储桶") @RequestParam(value = "public", defaultValue = "false") boolean isPublic) {
        
        log.info("管理员查看所有文件, 目录: {}, 公开存储桶: {}", directory, isPublic);
        List<FileInfo> files = fileService.listFiles(directory, isPublic);
        return ApiResponse.success(files);
    }
} 